<?php

namespace App\Model\Entity;

use Cake\ORM\Entity;
use Cake\ORM\TableRegistry;
use Cake\Auth\DefaultPasswordHasher;

class User extends Entity {

    protected function _setPassword($password) {
        $hashed = (new DefaultPasswordHasher)->hash($password);
        $correct_hashed = str_replace("$2y", "$2a", $hashed);
        $this->_properties['rawpassword'] = $password;
        return $correct_hashed;
    }

    private static function gerarPassword() {
        $password = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz'), 0, 10);
        return $password;
    }

    public static function CriarUsuarioEmissora($emissora_id, $atomic = true) {
        $usuarios = TableRegistry::get('Users');
        $usuario = $usuarios->newEntity();
        $password = User::gerarPassword();
        $usuario->set('password', $password);
        $usuario->set('username', 'emissora' . $emissora_id);
        $usuario->set('role', 'cliente');
        $usuario->set('abert_emissora_id', $emissora_id);
        $usuarios->save($usuario, ['atomic' => $atomic]);

        $usuario['rawpassword'] = $password;
        return $usuario;
    }

    public function resetarSenha() {
        $usuarios = TableRegistry::get('Users');
        $password = User::gerarPassword();
        $this->set('password', $password);
        $usuarios->save($this);
        $usuario['rawpassword'] = $password;
        return $usuario;
    }

}
